/**
 * All Rights Reserved , Copyright (C) 2020 , 青岛鼎信通讯股份有限公司
 * <p>
 * PmTaskService
 * 任务管理
 * <p>
 * 修改纪录
 * 2020-05-14 版本：1.0 wushenghong 创建。
 *
 * @version 版本：1.0
 * @author 作者：wushenghong
 * 创建日期：2020-05-14
 */
package com.topscomm.pm.service.impl;

import com.topscomm.basic.BasicEntity;
import com.topscomm.basic.util.PrimaryKeyUtil;
import com.topscomm.pm.pojo.PmTaskEntity;
import com.topscomm.pm.service.IPmTaskService;
import com.topscomm.pm.service.impl.auto.PmTaskServiceAuto;
import com.topscomm.pub.util.ConvertUtil;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Map;

@Service(value = "pmTaskService")
@Scope(value = "singleton")
public class PmTaskService extends PmTaskServiceAuto implements IPmTaskService {
    /**
     * @param entity
     * @throws
     * @author: wushenghong
     * @date: 2020-05-14
     * @description:单号生成
     * @modify:
     */
    @Override
    protected void beforeInsert(BasicEntity entity) {
        super.beforeInsert(entity);
        if (entity.getId() <= 0) {// 赋值Id和单号
            long[] arrayId = PrimaryKeyUtil.GeneIDs(entity.getTableName(), 1);
            entity.setId(arrayId[0]);
            String docNo = String.valueOf(arrayId[0]);
            docNo = docNo.substring(0, 6) + docNo.substring(9);
            entity.setValue(PmTaskEntity.FieldDocno, docNo);
        }
    }

    /**
     * @param map
     * @author: wushenghong
     * @date: 2020-06-04
     * @description:取消任务并将当前节点审批通过
     * @modify:
     */
    @Transactional
    public boolean executeCancelTask(Map map) {
        String taskId = ConvertUtil.convertToString(map.get("taskId"));
        String cancelReason = ConvertUtil.convertToString(map.get("cancelReason"));
        PmTaskEntity pmTaskEntity = this.queryById(taskId);
        if (pmTaskEntity != null) {
            pmTaskEntity.setTaskstate("0");
            pmTaskEntity.setCanceltime(new Date());
            pmTaskEntity.setCancelreason(cancelReason);
            this.updateEntity(pmTaskEntity);//更新任务取消信息
            return true;
        } else {
            return false;
        }
    }


    /**
     * @param paraMap
     * @author: wushenghong
     * @date: 2020-07-20
     * @description:工作日志补录
     * @modify:
     */
//    @Transactional(rollbackFor = Exception.class)
//    public void supplementTaskLog(Map<String, Object> paraMap) {
//        String ids = ConvertUtil.convertToString(paraMap.get("ids"));
//        StringBufferProxy sql = new StringBufferProxy();
//        // 查询待补录工作日志的任务
//        sql.appendSingle("id in ({0})", ids);
//        List<PmTaskEntity> pmTaskEntityList = this.queryByWhere(sql.toString());
//        sql.clear();
//        if (pmTaskEntityList.size() > 0) {
//            for (PmTaskEntity pmTaskEntity : pmTaskEntityList) {
//                creatTaskLog(pmTaskEntity);
//            }
//        }
//    }

    //工作日志信息生成
//    @Transactional(rollbackFor = Exception.class)
//    public void creatTaskLog(PmTaskEntity entity) throws ServiceException {
//        Map<String, Object> taskLogApplyMap = new HashMap<>();
//        PmTaskLogService pmTaskLogService = (PmTaskLogService) SpringUtil.getBean("pmTaskLogService");
//        FlowDatacodeCache flowDatacodeCache = (FlowDatacodeCache) SpringUtil.getBean("flowDatacodeCache");
//        //当前任务相关信息
//        Long projectId = entity.getProjectid();
//        Date actualStartDate = DateUtil.getZreoOfDay(entity.getActualstarttime());//任务点击开始的时间
//        Date planEndDate = DateUtil.getZreoOfDay(entity.getEndtime());//任务计划结束时间，日志生成的结束条件
//        String leaderCode = entity.getLeadercode();
//        String leaderName = entity.getLeadername();
//        String participantCodes = entity.getParticipantcodes();
//        String participantNames = entity.getParticipantnames();
//        if (leaderCode == null || leaderName == null) {
//            throw new ServiceException("所选任务中任务负责人信息不可以为空！");
//        }
//        // 任务参与人信息
//        List<String> participantCodeListTemp = new ArrayList<String>();
//        List<String> participantNameListTemp = new ArrayList<String>();
//        if (participantCodes != null && participantNames != null) {
//            participantCodeListTemp = Arrays.asList(participantCodes.split(","));
//            participantNameListTemp = Arrays.asList(participantNames.split(","));
//        }
//        //调用Arrays.asList()生产的List的add、remove方法时报异常,这样转换处理
//        List<String> participantCodeList = new ArrayList<String>(participantCodeListTemp);
//        List<String> participantNameList = new ArrayList<String>(participantNameListTemp);
//        //任务负责人添加至参与人
//        participantCodeList.add(leaderCode);
//        participantNameList.add(leaderName);
//        // 日期边界值
//        Date startDate = DateUtil.getZreoOfDay(entity.getStarttime());//任务计划开始时间，日志生成的开始条件
//        Date endDate = actualStartDate.getTime() >= planEndDate.getTime() ? planEndDate : actualStartDate;// 日志生成的结束条件
//        Date tempStartDate = null;
//        List<BasicEntity> entities = new ArrayList<>();
//        long days = cn.hutool.core.date.DateUtil.between(startDate, endDate, DateUnit.DAY, false);
//        // 循环插入
//        if (days < 0) {
//            return;
//        }
//        Map<String, Object> orgAndDeptMap = new HashMap<>();
//        List<Map<String, Object>> flowidList = new ArrayList<>();
//        for (int i = 0; i < participantCodeList.size(); i++) {
//            orgAndDeptMap = queryOrgAndDeptByCode(participantCodeList.get(i));
//            flowidList = flowDatacodeCache.getApprovalFlowListMap("ApprovalFlow_PmTaskLog", participantCodeList.get(i), "sortcode");
//            for (int j = 0; j <= days; j++) {
//                tempStartDate = DateUtils.addDays(startDate, j);
//                // 避免重复插入
//                StringBufferProxy sql = new StringBufferProxy();
//                String tempStartDateString = cn.hutool.core.date.DateUtil.formatDate(tempStartDate);
//                sql.appendSingle("taskid = {0} and finishtime = {1} and usercode = '{2}'", entity.getId(), SQLAdapter.toDateLong(tempStartDateString + " 00:00:00"), participantCodeList.get(i));
//                List<PmTaskLogEntity> pmTaskLogEntityList = pmTaskLogService.queryByWhere(sql.toString());
//                sql.clear();
//                // 判断当前日期是否工作日 且 日志当前参与人日志未生成
//                if (isWorkDate(projectId, tempStartDate) && pmTaskLogEntityList.size() == 0) {
//                    PmTaskLogEntity pmTaskLogEntity = new PmTaskLogEntity();
//                    taskLogApplyMap.put("projectid", entity.getProjectid());
//                    taskLogApplyMap.put("taskid", entity.getId());
//                    taskLogApplyMap.put("name", entity.getName());
//                    taskLogApplyMap.put("type", entity.getTasktype());
//                    taskLogApplyMap.put("content", entity.getExplain());
//                    taskLogApplyMap.put("finishtime", tempStartDate);
//                    taskLogApplyMap.put("username", participantNameList.get(i));
//                    taskLogApplyMap.put("usercode", participantCodeList.get(i));
//                    taskLogApplyMap.put("orgcode", orgAndDeptMap.get("orgcode"));
//                    taskLogApplyMap.put("orgname", orgAndDeptMap.get("orgname"));
//                    taskLogApplyMap.put("deptcode", orgAndDeptMap.get("deptcode"));
//                    taskLogApplyMap.put("deptname", orgAndDeptMap.get("deptname"));
//                    taskLogApplyMap.put("docdate", tempStartDate);
//                    taskLogApplyMap.put("flowid", flowidList.size() > 0 ? flowidList.get(0).get("id") : 0);
//                    pmTaskLogEntity.convertFromMap(taskLogApplyMap);
//                    entities.add(pmTaskLogEntity);
//                    taskLogApplyMap.clear();
//                }
//            }
//            orgAndDeptMap.clear();
//            flowidList.clear();
//        }
//        // 批量插入
//        if (entities.size() > 0) {
//            pmTaskLogService.insertBatch(entities);
//            // 系统session
//            CboUserService cboUserService = (CboUserService) SpringUtil.getBean("cboUserService");
//            CboDeptService cboDeptService = (CboDeptService) SpringUtil.getBean("cboDeptService");
//            CboOrgService cboOrgService = (CboOrgService) SpringUtil.getBean("cboOrgService");
//            List<CboUserEntity> cboUserEntities = cboUserService.queryByWhere(" code = 'QuartzUser' ");
//            List<CboDeptEntity> cboDeptEntities = cboDeptService.queryByWhere(" code = 'D11803'");
//            List<CboOrgEntity> cboOrgEntities = cboOrgService.queryByWhere(" code ='D1'");
//            SessionUserBean sessionUserBean = new SessionUserBean();
//            if (cboUserEntities.size() > 0 && cboDeptEntities.size() > 0 && cboOrgEntities.size() > 0) {
//                sessionUserBean.setUser(cboUserEntities.get(0));
//                sessionUserBean.setDept(cboDeptEntities.get(0));
//                sessionUserBean.setWorkDept(cboDeptEntities.get(0));
//                sessionUserBean.setOrg(cboOrgEntities.get(0));
//                sessionUserBean.setWorkOrg(cboOrgEntities.get(0));
//            }
//            // 遍历提交单据
//            for (BasicEntity pmTaskLogEntity : entities) {
//                // 赋值单号及提交时间
//                String docNo = String.valueOf(pmTaskLogEntity.getId());
//                docNo = docNo.substring(0, 6) + docNo.substring(9);
//                pmTaskLogEntity.setValue("docno", docNo);
//                pmTaskLogEntity.setValue("submitdate", new Date());
//                Map<String, Object> dataMap = pmTaskLogEntity.convertToMap();
//                StringBufferProxy mailtitle = new StringBufferProxy();
//                mailtitle.appendSingle("{0}的工作日志待提交，任务：{1}",
//                        DateUtil.dateToString(ConvertUtil.convertToDate(dataMap.get("finishtime")), "yyyy-MM-dd"), dataMap.get("name"));
//                pmTaskLogService.executeSubmit((TapEntity) pmTaskLogEntity, mailtitle.toString(), sessionUserBean);
//            }
//        }
//    }
//
//    /**
//     * @author: wushenghong
//     * @date: 2020/6/6
//     * @description: 根据工号查询部门组织信息
//     */
//    private Map<String, Object> queryOrgAndDeptByCode(String code) {
//        Map<String, Object> orgAndDeptMap = new HashMap<>();
//        CboOrgService cboOrgService = (CboOrgService) SpringUtil.getBean("cboOrgService");
//        CboDeptService cboDeptService = (CboDeptService) SpringUtil.getBean("cboDeptService");
//        StringBufferProxy sql = new StringBufferProxy();
//        sql.appendSingle("id in (select orgid from cbouser where code = '{0}')", code);
//        List<CboOrgEntity> cboOrgEntityList = cboOrgService.queryByWhere(sql.toString());
//        sql.clear();
//        sql.appendSingle("id in (select deptid from cbouser where code = '{0}')", code);
//        List<CboDeptEntity> cboDeptEntityList = cboDeptService.queryByWhere(sql.toString());
//        sql.clear();
//        orgAndDeptMap.put("orgcode", cboOrgEntityList.size() > 0 ? cboOrgEntityList.get(0).getCode() : "");
//        orgAndDeptMap.put("orgname", cboOrgEntityList.size() > 0 ? cboOrgEntityList.get(0).getName() : "");
//        orgAndDeptMap.put("deptcode", cboDeptEntityList.size() > 0 ? cboDeptEntityList.get(0).getCode() : "");
//        orgAndDeptMap.put("deptname", cboDeptEntityList.size() > 0 ? cboDeptEntityList.get(0).getFullname() : "");
//        return orgAndDeptMap;
//    }
//
//    //判断是否是工作日
//    private boolean isWorkDate(Long projectId, Date date) {
//        StringBufferProxy sql = new StringBufferProxy();
//        String datePure = cn.hutool.core.date.DateUtil.formatDate(date);//过滤日期格式
//        sql.appendSingle(" enabled=1 ");
//        sql.appendSingle("and projectid = {0} and calendardate = {1}", projectId, SQLAdapter.toDateLong(datePure + " 00:00:00"));
//        PmCalendarService pmCalendarService = (PmCalendarService) SpringUtil.getBean("pmCalendarService");
//        List<PmCalendarEntity> pmCalendarEntityList = pmCalendarService.queryByWhere(sql.toString());
//        if (pmCalendarEntityList.size() > 0) {
//            PmCalendarEntity pmCalendarEntity = pmCalendarEntityList.get(0);
//            String calenderType = pmCalendarEntity.getCalendartype();
//            //工作日或者加班日
//            return "01".equals(calenderType) || "04".equals(calenderType);
//        }
//        return false;
//    }
}
